<script setup lang="ts">
import { useRoute } from "vue-router";
import { ref, watchEffect, onMounted } from "vue";
import myAxios from "../plugins/MyAxios.ts";
import UserCardList from "../components/UserCardList.vue";
import { showFailToast, showSuccessToast } from "vant/es";
import type { UserType } from "../models/user";

const route = useRoute();
const { tags } = route.query;
const userList = ref<UserType[]>([]);
const isLoading = ref(false);
const error = ref<string | null>(null);

// 安全解析 JSON 标签
const safeParseTags = (tags: string | string[] | undefined): string[] => {
  if (!tags) return [];
  try {
    const parsed = typeof tags === 'string' ? JSON.parse(tags) : tags;
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
};

const checked = ref(false);

const loadData = async () => {
  try {
    isLoading.value = true;
    error.value = null;

    if (checked.value) {
      // 心动模式 - 智能匹配
      const res = await myAxios.get('user/match', {
        params: {
          num: 5
        }
      });
      
      if (res.status === 0) {
        showSuccessToast("智能匹配成功");
        userList.value = res.data.map((user: any) => ({
          ...user,
          tags: safeParseTags(user.tags)
        }));
      } else {
        showFailToast("智能匹配失败");
        userList.value = [];
      }
    } else {
      // 推荐模式 - 浏览推荐用户
      const params = { 
        pageNum: 1, 
        pageSize: 10, 
        ...(tags && { tags }) 
      };
      
      const res = await myAxios.get('user/recommend', { params });

      if (res.data?.records) {
        userList.value = res.data.records.map((user: any) => ({
          ...user,
          tags: safeParseTags(user.tags)
        }));
      } else {
        userList.value = [];
      }
    }
  } catch (err) {
    console.error('请求失败:', err);
    error.value = '加载用户数据失败';
    showFailToast('加载用户数据失败，请重试');
    userList.value = [];
  } finally {
    isLoading.value = false;
  }
};

// 监听心动模式切换
watchEffect(() => {
  loadData();
});

const handleModeChange = (value: boolean) => {
  if (value) {
    showSuccessToast('已开启心动模式');
  } else {
    showSuccessToast('已关闭心动模式');
  }
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});


</script>

<template>
  <div class="index-page">
    <!-- 心动模式切换 -->
    <div class="mode-switch-container">
      <van-cell center title="心动模式" class="mode-switch-cell">
        <template #right-icon>
          <van-switch 
            v-model="checked" 
            size="24px"
            @change="handleModeChange"
            :disabled="isLoading"
          />
        </template>
      </van-cell>
      <div class="mode-description">
        <van-icon name="heart" size="16" />
        <span>{{ checked ? '开启智能匹配，发现更多可能' : '浏览推荐用户，寻找志同道合的朋友' }}</span>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <van-loading size="24px" vertical>正在加载用户数据...</van-loading>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <van-empty 
        image="error" 
        :description="error"
        class="error-state"
      >
        <van-button type="primary" @click="refreshData">
          <van-icon name="replay" size="16" />
          重新加载
        </van-button>
      </van-empty>
    </div>
    
    <!-- 用户列表 -->
    <UserCardList 
      v-else
      :user-list="userList" 
      :loadings="isLoading"
      @refresh="refreshData"
    />
  </div>
</template>

<style scoped>
.index-page {
  min-height: 100vh;
  background: transparent;
}

.mode-switch-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  margin: 16px;
  padding: 16px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: fadeInUp 0.6s ease-out;
}

.mode-switch-cell {
  background: transparent;
  border-radius: 12px;
  margin-bottom: 12px;
}

.mode-description {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #7f8c8d;
  font-size: 14px;
  padding: 8px 16px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 12px;
  border-left: 3px solid #667eea;
}

.mode-description .van-icon {
  color: #667eea;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 50vh;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  margin: 16px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.error-container {
  margin: 16px;
}

.error-state {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 40px 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 深度选择器优化 Vant 组件样式 */
:deep(.van-cell__title) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

:deep(.van-switch--on) {
  background-color: #667eea;
}

:deep(.van-switch__node) {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

:deep(.van-switch--disabled) {
  opacity: 0.6;
}

:deep(.van-loading__text) {
  color: #667eea;
  font-weight: 500;
  margin-top: 12px;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

:deep(.van-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

:deep(.van-button--primary:active) {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mode-switch-container {
    margin: 12px;
    padding: 12px;
  }
  
  .mode-description {
    font-size: 13px;
    padding: 6px 12px;
  }
}
</style>